package com.gxa.controller;

import com.gxa.entity.R;
import com.gxa.entity.User;
import com.gxa.utils.Md5Utils;
import com.gxa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录方法
     * *哪里进来的就返回到哪个页面去
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/login")
    public R login(String username,String password){
        //把用户输入的密码设置为Md5码的方式进行获取
//        String passwords=user.getPassword();
        String newPassword= Md5Utils.setMD5(password);
//        user.setPassword(newPassword);
        System.out.println(newPassword);
        //根据用户名和密码寻找到User对象
        User loginUser = userService.login(username,newPassword);
        if(loginUser != null){
            redisTemplate.opsForValue().set("user",loginUser);
            return R.success(200,loginUser,"登录成功!");
        }
        return R.Error(500,"登陆失败！账号或密码有误！");
    }

    /**
     * 获得登录用户
     * @return
     */

    @GetMapping("/getUser")
    public User getUser(){
        User user=(User) redisTemplate.opsForValue().get("user");
        System.out.println(user);
        if (user!=null){
            return user;
        }
        else return null;
    }

    /**
     * 退出登录
     */
    @GetMapping("/loginOut")
    public String loginOut(){
      redisTemplate.opsForValue().set("user",null);
        return "ok";
    }

}
